package com.springx.examples.showcase.service;

import com.google.common.collect.Maps;
import com.springx.examples.showcase.entity.Resource;
import com.springx.examples.showcase.enums.ResourceEnum;
import com.springx.examples.showcase.repository.mybatis.ResourceMapper;
import com.springx.examples.showcase.vo.tree.ZTreeNoneAjaxVo;
import com.springx.examples.showcase.vo.tree.ZTreeResourceVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * Created by roman_000 on 2015/7/12.
 */
@Service
@Transactional
public class ResourceService extends BaseService<Resource> {
    @Autowired
    private ResourceMapper resourcesMapper;

    @Transactional(readOnly = true)
    public List<ZTreeResourceVo> findChildren(Map<String, Object> params) {
        return resourcesMapper.findChildren(params);
    }


    /**
     * 查找下级节点数量
     *
     * @param parentId
     * @return
     */
    @Transactional(readOnly = true)
    public int findChildrenCount(Long parentId) {
        Example example = new Example(Resource.class);
        example.createCriteria().andEqualTo("parentId", parentId);
        int count = resourcesMapper.selectCountByExample(example);
        return count;
    }

    /**
     * 节点排序
     *
     * @param id1
     * @param id2
     */
    public void sort(Long id1, Long id2) {
        Resource resource1 = resourcesMapper.selectByPrimaryKey(id1);
        Resource resource2 = resourcesMapper.selectByPrimaryKey(id2);
        Long sort = resource1.getSort();
        resource1.setSort(resource2.getSort());
        resource2.setSort(sort);
        resourcesMapper.updateByPrimaryKeySelective(resource1);
        resourcesMapper.updateByPrimaryKeySelective(resource2);
    }

    /**
     * 保存记录
     */
    public void save(Resource resource) {
        this.insert(resource);
        resource.setSort(resource.getId());
        this.updateByPrimaryKeySelective(resource);
    }

    /**
     * 角色选择资源数据
     */
    public List<ZTreeNoneAjaxVo> selectTreeResourceChildren(Map<String, Object> params) {
        return resourcesMapper.selectTreeResourceChildren(params);
    }

    /**
     * 获取所有的资源,最好缓存 用于面包屑
     * @return
     */
    public Map<String, Resource> selectAllCrumbs() {
        Example example = new Example(Resource.class);
        example.createCriteria().andEqualTo("type", ResourceEnum.TYPE.MENU.getKey());
        List<Resource> resourceList = resourcesMapper.selectByExample(example);
        Map<String, Resource> result = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(resourceList)) {
            for (Resource resource : resourceList) {
                result.put(resource.getName(), resource);
            }
        }
        return result;
    }

}
